const db = wx.cloud.database(); // 初始化数据库
Page({
  data: {
    radio: '通过',
    showAddress: false,
    showTag: false,
    addresslist: ['佛山校区', '广州校区'],
    addressresult: [],
    leguetags: ['校级','院级','社联协会','志愿服务','组织策划','技能学习','体育运动','学术交流','宣传制作','音乐舞蹈','行政办公','实践DIY'],
    leguetagresult: [],
    lifeImages: [],
    consultImages: [],
    legueName: '',
    introduction: '',
    demand: '无',
    qq: '',
    weixin: '',
    username: '',
    class: '',
    phone:'',
    email: '',
    lifeImagesIds: [],
    consultImagesIds: [],
    like: 0,
    legueId: '',
    status: 1,
    nowLifeImagesIndex: 0,
    nowConsultImageIndex: 0,
    _id: ''
  },
  onReview(event) {
    const { name } = event.currentTarget.dataset;

    this.setData({
      radio: name,
    });
    if(this.data.radio == '通过') {
      this.setData({
        status: 1
      })
    }
    if(this.data.radio == '不通过') {
      this.setData({
        status: 2
      })
    }
  },
  onNameChange(event) {
    this.setData({
      legueName: event.detail
    })
  },
  onIntroductionChange(event) {
    this.setData({
      introduction: event.detail
    })
  },
  onQQChange(event) {
    this.setData({
      qq: event.detail
    })
  },
  onDemandChange(event) {
    this.setData({
      demand: event.detail
    })
  },
  onUserNameChange(event) {
    this.setData({
      username: event.detail
    })
  },
  onClassChange(event) {
    this.setData({
      class: event.detail
    })
  },
  onPhoneChange(event) {
    this.setData({
      phone: event.detail
    })
  },
  onLikeChange(event) {
    this.setData({
      like: parseInt(event.detail)
    })
  },
  onWeixinChange(event) {
    this.setData({
      weixin: event.detail
    })
  },
  onEmailChange(event) {
    this.setData({
      email: event.detail
    })
  },
  addressChange(event) {
    this.setData({
      addressresult: event.detail
    });
  },
  tagChange(event) {
    if(event.detail.length <= 3) {
      this.setData({
        leguetagresult: event.detail,
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '最多选取三个',
      })
    }

  },
  addressToggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.addressbox-${index}`);
    checkbox.toggle();
  },
  tagsToggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.tagsbox-${index}`);
    checkbox.toggle();
  },
  noop() {},
  showAddressPopup() {
    this.setData({showAddress:true})
  },
  showTagPopup() {
    this.setData({ showTag: true });
  },
  popupClose() {
    this.setData({ showAddress: false })
    this.setData({ showTag: false });
  },
  afterlifeRead(event) {
    const { file } = event.detail;
    this.data.lifeImages.push({ url: event.detail.file.path })
    this.setData({
      lifeImages: this.data.lifeImages
    })
  },
  deletelifeImage(event) {
    this.data.lifeImages.splice(event.detail.index, 1)
    this.setData({
      lifeImages: this.data.lifeImages,
      nowLifeImagesIndex: this.data.lifeImages.length
    })
  },
  afterconsultRead(event) {
    const { file } = event.detail;
    this.data.consultImages.push({ url: event.detail.file.path })
    this.setData({
      consultImages: this.data.consultImages
    })
  },
  deleteconsultImage(event) {
    
    this.data.consultImages.splice(event.detail.index, 1)
    this.setData({
      consultImages: this.data.consultImages,
      nowConsultImageIndex: this.data.consultImages.length
    })
  },
  submit() {
    if(this.data.qq != ''){
      var rsNum= /^\d+$/.test(this.data.qq);
      if(!rsNum) {
        setTimeout(()=>{
          wx.showToast({
              title: 'QQ群号只能是数字',
              icon: 'none'
          })
        },500)
        return
      }
    }
    var phonenum = /^\d+$/.test(this.data.phone)
    if(this.data.legueName == '') {
      wx.showToast({
        icon :'none',
        title: '社团名字不能为空',
      })
    }
    else if(this.data.addressresult.length == 0) {
      wx.showToast({
        icon :'none',
        title: '至少选择一个校区',
      })
    }
    else if(this.data.leguetagresult.length == 0) {
      wx.showToast({
        icon :'none',
        title: '至少选择一个属性',
      })
    }
    else if(this.data.username == '') {
      wx.showToast({
        icon :'none',
        title: '负责人不能为空',
      })
    }
    else if(this.data.class == '') {
      wx.showToast({
        icon :'none',
        title: '班级不能为空',
      })
    }
    else if(this.data.phone == '') {
      wx.showToast({
        icon :'none',
        title: '手机不能为空',
      })
    }
    else if(!phonenum) {
      setTimeout(()=>{
        wx.showToast({
            title: '手机格式不正确',
            icon: 'none'
        })
      },500)
    }
    else {
      var _this = this
      wx.showModal({
        title:'审核提示',
        content: '若设为通过后该条记录将被展示出来',
        success (res) {
          if (res.confirm) {
            wx.showLoading({
              title:'审核提交中'
            })
            console.log(_this.data.lifeImages)
            for(var i = 0; i < _this.data.nowLifeImagesIndex; i++) {
              _this.data.lifeImagesIds[i] = _this.data.lifeImages[i].url
            }
            for(var i = 0; i < _this.data.nowConsultImageIndex; i++) {
              _this.data.consultImagesIds[i] = _this.data.consultImages[i].url
            }
            _this.setData({
              lifeImagesIds: _this.data.lifeImagesIds,
              consultImagesIds: _this.data.consultImagesIds
            })


            // 上传图片到云存储
            let promiseArr = [];
            for (let i = _this.data.nowLifeImagesIndex; i < _this.data.lifeImages.length; i++) {
              promiseArr.push(new Promise((reslove, reject) => {
                let item = _this.data.lifeImages[i].url;
                let suffix = /\.\w+$/.exec(item)[0]; // 正则表达式，返回文件扩展名
                wx.cloud.uploadFile({
                  cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                  filePath: item, // 小程序临时文件路径
                  success: res => {
                    // 返回文件 ID
                    _this.setData({
                      lifeImagesIds: _this.data.lifeImagesIds.concat(res.fileID)
                    });
                    reslove();
                  },
                  fail: console.error
                })
              }));
            }

            for (let i = _this.data.nowConsultImageIndex; i < _this.data.consultImages.length; i++) {
              promiseArr.push(new Promise((reslove, reject) => {
                let item = _this.data.consultImages[i].url;
                let suffix = /\.\w+$/.exec(item)[0]; // 正则表达式，返回文件扩展名
                wx.cloud.uploadFile({
                  cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
                  filePath: item, // 小程序临时文件路径
                  success: res => {
                    // 返回文件 ID
                    _this.setData({
                      consultImagesIds: _this.data.consultImagesIds.concat(res.fileID)
                    });
                    reslove();
                  },
                  fail: console.error
                })
              }));
            }

            Promise.all(promiseArr).then(res => {
              // 插入数据
              wx.cloud.callFunction({
                name: 'updateLegueStatus',
                data :{
                  _id: _this.data.legueId,
                  legueName: _this.data.legueName,
                  introduction: _this.data.introduction,
                  addressresult: _this.data.addressresult,
                  leguetagresult: _this.data.leguetagresult,
                  demand: _this.data.demand,
                  username: _this.data.username,
                  class: _this.data.class,
                  phone:_this.data.phone,
                  qq: _this.data.qq,
                  weixin: _this.data.weixin,
                  email: _this.data.email,
                  lifeImagesIds: _this.data.lifeImagesIds,
                  consultImagesIds: _this.data.consultImagesIds,
                  like: _this.data.like,
                  status: _this.data.status
                },
                complete: res => {
                  wx.hideLoading();
                  wx.showToast({
                    title: '发布成功',
                    duration: 3000,
                    success: function () {
                    setTimeout(function () {
                        wx.reLaunch({
                          url: '../legue/leguereview',
                        })
                      }, 2000);
                    }
                   })
                }
              })
            });
          } else if (res.cancel) {
          }
        }
      })
      
    }
  },
  delete(event) {
    var _this = this
    wx.showModal({
      title: '删除提示',
      content: '将删除此条记录在数据库中的信息，不可恢复',
      success (res) {
        if (res.confirm) {
          wx.showLoading({
            title:'删除中'
          })
          wx.cloud.callFunction({
            name: 'deleteLegueById',
            data: {
              _id: _this.data._id
            },
            complete: res => {
              wx.hideLoading();
              wx.showToast({
                title: '删除成功',
                duration: 3000,
                success: function () {
                setTimeout(function () {
                    wx.reLaunch({
                      url: '../legue/leguereview',
                    })
                  }, 2000);
                }
              })
            }
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '取消删除',
            icon:'none'
          })
        }
      }
    })
  },
  onLoad: function (options) {
    let detail = JSON.parse(options.legueDetail)
    this.setData({
      _id:detail._id,
      addressresult: detail.addressresult,
      leguetagresult: detail.leguetagresult,
      legueName: detail.legueName,
      introduction: detail.introduction,
      demand: detail.demand,
      qq: detail.qq,
      weixin: detail.weixin,
      email: detail.email,
      like: detail.like,
      username: detail.username,
      class: detail.class,
      phone: detail.phone,
      legueId: detail._id,
      status: detail.status,
    })
    for(var i = 0; i < detail.lifeImagesIds.length; i++) {
      this.data.lifeImages.push({ url: detail.lifeImagesIds[i] })
    }
    for(var i = 0; i < detail.consultImagesIds.length; i++) {
      this.data.consultImages.push({ url: detail.consultImagesIds[i] })
    }
    this.setData({
      consultImages: this.data.consultImages,
      lifeImages: this.data.lifeImages,
      nowLifeImagesIndex: this.data.lifeImages.length,
      nowConsultImageIndex: this.data.consultImages.length
    })
    if(detail.status == 1 || detail.status == 0) {
      this.setData({
        status: 1,
        radio: '通过'
      })
    } else {
      this.setData({
        radio: '不通过'
      })
    }
  },
});